import React, { PropTypes, PureComponent, Fragment } from 'react';
import {
  PrimaryC,
  DATA_ENTRY,
  InputNumberC,
  ModalC,
  PrimaryGhostC,
  codeType,
  TradingDirectC,
  TradingTypeC,
  InputC,
  SingleDateC,
  AdvancedSearch,
  ProductGroupSepC,
  SelectC,
  NoQueryC,
  TableC,
  FirstHeaderC,
  SecondHeaderC,
  TradingMarketC,
} from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Input, Button, message, Table, Divider, DatePicker, Select, Modal } from 'antd';
import style from './index.less';
import { connect } from 'dva';
import OrderFormC from './orderFormC';
import { uniqueKey } from '../../../../utils/commonFunc';

import { timeThursdays } from 'd3-time';
const { TextArea } = Input;
const FormItem = Form.Item;
const FormItemLayout = {
  labelCol: {
    xl: { span: 10, offset: 0 },
    xxl: { span: 8, offset: 0 },
  },
  wrapperCol: {
    xl: { span: 13, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};

class AddOrderC extends PureComponent {
  static defaultProps = {
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //详情
    type: undefined, //当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    isShow: false, //二次确认模态框显示隐藏
    querys: {}, //二次确认详情数据
    isCanOrder: true, //组合是否可以下达 默认可以
    trailColumns: [], //试算结果列表
    trailDataSource: [], //试算结果数据
    trailModel: false, //试算模态框
    productCode: undefined, //产品code
    portfolioCode: undefined, //组合code
    uid: '',
  };
  componentDidMount() {
    this.props.onRef(this);
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }
  //用户点击下达或确定按钮
  onOk = () => {
    const { type, isStop, position, info } = this.props;
    if (!this.state.isCanOrder && type == 1) {
      message.warning(this.props.errorSetMsg);
      return;
    }
    const data = this.orderForm.getInfo();
    //校验页面数据
    if (!data) return;
    data.uid = this.state.uid;
    if (type == '1' && isStop == '停牌') {
      message.warning('该证券代码已经停牌，无法下达');
      return;
    }
    if (type == 1) {
      if (this.state.isShow) {
        this.confirmOk(data); //二次确认的确定 点击按钮
      } else {
        //指令下达需要二次确认
        this.setState({
          querys: data,
          isShow: true,
        });
      }
    } else {
      //簿记无需二次确认 直接请求后端
      this.confirmOk(data);
    }
  };
  //用户点击取消
  onCancel = () => {
    this.orderForm.reset();
    this.setState({
      isCanOrder: true,
    });
    this.props.onCancel();
  };
  confirmOk = (params) => {
    // console.log(params);
    //指令下达 簿记保存请求后台
    const {
      dispatch,
      type,
      user: { currentUser },
    } = this.props;
    if (type == 11) {
      //组合试算-港股通
      params = {
        portfolioId: params.portfolioid,
        productId: params.productid,
        type: 15,
        userId: params.userid,
        userName: params.username,
        businessType: '15',
        tenant: currentUser.tenant, //租户code
        uid: params.uid,
        trade15: {
          portfolioid: params.portfolioid,
          productid: params.productid,
          exchangecode: params.exchangecode,
          tradingcode: params.tradingcode,
          amount: params.amount,
          direction: params.direction,
          fee: params.fee, //
          investmentType: params.investmentType,
          price: params.price,
          remark: params.remark,
          secuabbr: params.secuabbr,
          totalPrice: params.totalPrice,
          type: params.type,
        },
      };
    }
    if (type == 2) {
      //簿记下达
      params.method = '0';
    }
    let url = type == 1 ? 'HKstockM/orderSave' : type == 11 ? 'portfolioTrialAddM/stockSave' : 'HKstockM/tradeBookSave';
    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (msg) => {
        if (msg) {
          if (type == 2 || type == 11) {
            //簿记下达成功
            this.onCancel(); //初始化form表单
            this.props.onOk();
          } else {
            //指令下达成功
            this.onCancel(); //初始化form表单
            this.handleCancel(); //关闭模态框
          }
        }
        const uid = uniqueKey();
        uid.then((r) => {
          this.setState({ uid: r });
        });
      },
    });
  };
  //二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };
  // 二次确认modal框
  showModal = () => {
    const { querys, isShow } = this.state;
    const { loading, type } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 1000,
      height: 1000,
      className: 'confirmOrder',
      confirmLoading: loading.effects['HKstockM/orderSave'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.onOk} onCancel={this.handleCancel}>
        <OrderFormC type={'3.1'} info={querys} />
      </ModalC>
    );
  };

  queryIsAccountConfigured = (value) => {
    if (value) {
      this.props.dispatch({
        //校验组合下是否有组合配置
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: value,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else {
      this.setState({
        isCanOrder: true,
      });
    }
  };
  //试算按钮点击
  trialOnClick = () => {
    const {
      type,
      user: { currentUser },
    } = this.props;
    const data = this.orderForm.getInfo();
    //校验页面数据
    if (!data) return;
    let obj = {};
    obj.method = '0';
    obj.type = 19;
    obj.productCode = this.state.productCode; //产品code
    obj.portfolioCode = this.state.portfolioCode; //组合code
    obj.tenant = currentUser.tenant; //租户code
    obj.businessType = 19;
    obj.userId = data.userid;
    obj.userName = data.username;
    obj.trade19 = { ...data };
    this.setState({ trailModel: true }, () => {
      this.props.dispatch({
        type: 'trailM/trialData',
        payload: obj,
        callback: (res) => {
          if (res) {
            this.setState({
              trailColumns: res.columns,
              trailDataSource: res.dataSource,
            });
          } else {
            this.setState({
              trailColumns: [],
              trailDataSource: [],
            });
          }
        },
      });
    });
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };

  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };
  render() {
    const { loading, type } = this.props;
    return (
      <div>
        <div>
          <OrderFormC
            type={this.props.type}
            portfolioOnChange={(e) => {
              this.props.portfolioOnChange(e);
              if (this.props.type == '1') this.queryIsAccountConfigured(e); //指令下达的时候进行校验组合是否配置
            }}
            tradingcodeOnChange={this.props.tradingcodeOnChange}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            onRef={(ref) => {
              this.orderForm = ref;
            }}
            investmentType={this.props.position.investmentType}
            lotSize={this.props.lotSize}
            optionTickSize={this.props.optionTickSize}
            money={this.props.money}
          />
        </div>
        <div style={{ marginTop: '20px' }} className={style.btnOperate}>
          {/* {this.props.type == 2 && <PrimaryC
                        loading={this.props.loading.effects['trailM/trialData'] === true}
                        onClick={() => this.trialOnClick()}
                        title={'试算'}
                        style={{ marginRight: "16px" }}
                    />} */}
          <PrimaryC loading={loading.effects['HKstockM/tradeBookSave'] === true} onClick={this.onOk} title={this.props.type == 1 ? '下达' : '确定'} />
          <PrimaryGhostC onClick={this.onCancel} title='取消' style={{ marginLeft: '16px' }} />
        </div>
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
        {this.state.trailModel && this.showTrail()}
      </div>
    );
  }
}
export default connect(({ HKstockM, userM: user, loading, trailM, isAccountConfiguredM }) => ({
  HKstockM,
  user,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
  isAccountConfiguredM,
}))(Form.create()(AddOrderC));
